
import Mock from 'mockjs'

//定义分页的数据
const data = Mock.mock({
    'list|10':[
        {
            name: '@cname()',
            address: '@city(true)',
            id: '@increment(1)', // 每次都增加1
            date:'@date(yyyy-MM-dd)'
        }
    ]
})

function getQuery(url,name){
    var index= url.indexOf('?');
    var zhi= url.substr(index+1);
     //[currentPage=1,pageSize=1]
    var zhis= zhi.split('&');
     for (let index = 0; index < zhis.length; index++) {
         const element = zhis[index];
          var zhi2=element.split('=');
          if(zhi2[0]==name)
          {
             var zhi3=zhi2[1];
             return zhi3;
          }
             
     }
}

//从data对象中解析list值
var {list}=data;
//定义分页get拦截请求
Mock.mock(/\/api\/get\/user/,'get',(options)=>{
 
    //api/get/user?currentPage=1&pageSize=1
    var url=options.url;
    //currentPage=1&pageSize=1
   
    //[currentPage,1]/[pageSize,1]
    var currentPage=getQuery(url,'currentPage');
    var pageSize=getQuery(url,'pageSize');
    console.info(currentPage+""+pageSize);
    //模拟做一个分页
    var start=(currentPage-1)*pageSize; //(当前页-1)*每页显示数
    var end=currentPage*pageSize;   //当前页*每页显示数
    //分页
   var list2= list.slice(start,end);//包前不包后

   //分析分页的公示
   //1页 10：0  10
   //2页 10: 10 20
   //3页 10: 20 30

    return {
        list:list2,
        total:list.length,
        status: 200,
        message: '获取新闻列表数据成功'
    }
})

//定义新增的拦截
Mock.mock('/api/post/add','post',(options)=>{

    //获取json字符串
    //JSON.parse()-把字符转为对象
    var zhi=JSON.parse(options.body);
    var d=new Date(zhi.date);
    var y=d.getFullYear();
    var m=d.getMonth()+1;
    var d=d.getDate();
    var d2=y+"-"+m+"-"+d
    //console.info(zhi.name)
    //通过mock产生新对象
    var obj=Mock.mock({
        name: zhi.name,
        address: zhi.address,
        id: '@increment(1)', // 每次都增加1
        date:d2
    })
    //把产生的对象添加到集合中
    list.push(obj);
    return{
        status: 200,
        message: '新增数据成功'
    }
   
})

//定义修改的拦截
Mock.mock('/api/put/edit','put',(options)=>{
    //把json字符串转为json对象
    var zhi=JSON.parse(options.body);
    list.some(user=>{
        //根据编号来定位
        if(user.id==zhi.id){
            //根据值做修改操作
            user.name=zhi.name;
            user.address=zhi.address;
            user.date=zhi.date;
        }
        return true;
    })
    return{
        status: 200,
        message: '修改数据成功'
    }
})
//定义删除的拦截
Mock.mock(/\/api\/delete\/sc/,'delete',(options)=>{
    var url=options.url
    var id=getQuery(url,'id');
    //
    var index= list.findIndex(item=>item.id==id);
    //
    list.splice(index,1);
    return{
        status: 200,
        message:'删除数据成功'
    }
})


